/*
 * comlan
 */

package com.promfy.wifi;

import java.util.List;

import android.content.Context;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.net.wifi.WifiManager.WifiLock;
import android.util.Log;

public class WifiAdmin
{
	public static final String SHARE_ME_SSID = "ShareMe";
	public static final String SHARE_ME_PWD = "ShareMe";
	private static final String TAG = "wire";
	//定义WifiManager对象
	private WifiManager mWifiManager;
	//定义WifiInfo对象
	private WifiInfo mWifiInfo;
	//扫描出的网络连接列表
	private List<ScanResult> mWifiList;
	//网络连接列表
	private List<WifiConfiguration> mWifiConfiguration;
	//定义一个WifiLock
	WifiLock mWifiLock;
	private Context context;
	//构造器
	public  WifiAdmin(Context context)
	{
		this.context = context;
		//取得WifiManager对象
		mWifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
	}

	public boolean isConnectedWithShareMe(){
		WifiInfo wifiInfo = mWifiManager.getConnectionInfo();
		String ssid = wifiInfo.getSSID();
		if(ssid.equals(SHARE_ME_SSID)){
			return true;
		}else {
			return false;
		}
	}
	
	public void connct (String ssid, String pwd){
		WifiManager wifi = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
		if (!wifi.isWifiEnabled()) { // 如果wifi没有开启，则开启。
			wifi.setWifiEnabled(true);
		}

		WifiConfiguration wc = new WifiConfiguration();
		wc.SSID = "\"" + ssid + "\""; // 配置wifi的SSID，即该热点的名称，如：TP-link_xxx
		wc.preSharedKey = "\"" + pwd + "\""; // 该热点的密码
		wc.hiddenSSID = true;
		wc.status = WifiConfiguration.Status.ENABLED;
		wc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
		wc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
		wc.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
		wc.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
		wc.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
		wc.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
		int res = wifi.addNetwork(wc);
		Log.d(TAG, "add Network returned " + res);
		boolean b = wifi.enableNetwork(res, true);
		Log.d(TAG, "enableNetwork returned " + b);
	}
	
	public List<ScanResult> getAvailableWifi(){
		 return mWifiManager.getScanResults();
	}
}
